package nl.renedegroot.android.intervalbeeper;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Map;
import java.util.Vector;
import java.util.Map.Entry;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.AssetFileDescriptor;
import android.graphics.Typeface;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class SoundsAdapter extends BaseAdapter
{

   private static final String TAG = "SoundsAdapter";
   private static final int[] STATIC_SOUNDS = { R.raw.corsica, R.raw.noiseyding, R.raw.ring_digital_03 };
   private static final long[] STATIC_VIBRATE= { 500L };
   private static String[] static_soundsNames;
   
   private Context mContext;

   
   private Vector<String> mCustomSounds;
   private Vector<Uri> mCustomSoundsFilenames;
   private OnSharedPreferenceChangeListener listener = new OnSharedPreferenceChangeListener()
   {
      public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key )
      {
         readPreferences( sharedPreferences );
      }
   };

   SoundsAdapter(Context context)
   {
      mContext = context;
      static_soundsNames = mContext.getResources().getStringArray( R.array.sounds_names );
      mCustomSounds = new Vector<String>();
      mCustomSoundsFilenames = new Vector<Uri>();
      
      SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences( mContext );
      sharedPreferences.registerOnSharedPreferenceChangeListener( listener  );
      readPreferences( sharedPreferences );
   }

   @SuppressWarnings("unchecked")
   private void readPreferences( SharedPreferences preferences )
   {
      Map<String, String> prefs = (Map<String, String>) preferences.getAll();
      for (Entry<String, String> entry : prefs.entrySet())
      {
         String name = entry.getKey();
         if( entry.getValue() instanceof String )
         {
            Uri file = Uri.parse( entry.getValue() );
            AssetFileDescriptor fd = null;
            try
            {
               fd = mContext.getContentResolver().openAssetFileDescriptor( file, "r" );
               mCustomSounds.add( name );
               mCustomSoundsFilenames.add( file );
            }
            catch (FileNotFoundException e)
            {
               Log.e( TAG, "Could not be added... :" + name );
            }
            finally
            {
               if( fd != null )
               {
                  try
                  {
                     fd.close();
                  }
                  catch (IOException e)
                  {
                     Log.w( TAG, "The file was not closed... :" + name );
                  }
               }
            }
         }
      }
      this.notifyDataSetChanged();
   }

   public int getCount()
   {
      return static_soundsNames.length + mCustomSounds.size();
   }

   public Object getItem( int position )
   {
      return position < static_soundsNames.length ? static_soundsNames[position] : mCustomSounds.get( position - static_soundsNames.length );
   }

   public long getItemId( int position )
   {
      return position;
   }

   public View getView( int position, View convertView, ViewGroup parent )
   {
      TextView view;
      if( mContext instanceof RegisterSoundActivity )
      {
         if( convertView == null )
         {
            LayoutInflater factory = LayoutInflater.from( mContext );
            view = (TextView) factory.inflate( R.layout.interval_row, null );
         }
         else
         {
            view = (TextView) convertView;
         }
         if( position < static_soundsNames.length )
         {
            view.setEnabled( false );
            view.setTypeface( view.getTypeface(), Typeface.ITALIC );
         }
         else
         {
            view.setEnabled( true );
            view.setTypeface( view.getTypeface(), Typeface.NORMAL );
         }
      }
      else
      {
         if( parent instanceof Spinner )
         {
            if( convertView == null )
            {
               LayoutInflater factory = LayoutInflater.from( mContext );
               view = (TextView) factory.inflate( android.R.layout.simple_spinner_item, null );
            }
            else
            {
               view = (TextView) convertView;
               view.setEnabled( true );
               view.setTypeface( view.getTypeface(), Typeface.NORMAL );
            }
         }
         else
         {
            if( convertView == null )
            {
               LayoutInflater factory = LayoutInflater.from( mContext );
               view = (TextView) factory.inflate( android.R.layout.simple_spinner_dropdown_item, null );
            }
            else
            {
               view = (TextView) convertView;
               view.setEnabled( true );
               view.setTypeface( view.getTypeface(), Typeface.NORMAL );
            }
         }
      }
      view.setText( position < static_soundsNames.length ? static_soundsNames[position] : mCustomSounds.get( position - static_soundsNames.length ) );
      return view;
   }

   public SoundTimer createSoundTimer( int sound, long period )
   {
      SoundTimer timer;
      if( sound < STATIC_SOUNDS.length )
      {
         String soundName = static_soundsNames[sound];
         timer = new SoundTimer(mContext, soundName, period, 0L,  STATIC_SOUNDS[sound]);
      }
      else if ( sound < STATIC_SOUNDS.length + STATIC_VIBRATE.length )
      {
         String soundName = static_soundsNames[sound];
         timer = new SoundTimer(mContext, soundName, period, 0L,  STATIC_VIBRATE[sound-STATIC_SOUNDS.length]);
      }
      else
      {
         sound = sound - STATIC_SOUNDS.length - STATIC_VIBRATE.length;
         String soundName = mCustomSounds.get( sound );
         Uri fileUri = mCustomSoundsFilenames.get( sound );
         timer = new SoundTimer(mContext, soundName, period, 0L, fileUri);
      }
      return timer;
   }

   public SoundTimer createSoundTimer( int sound )
   {
      return createSoundTimer( sound, 0L );
   }
   
   public void removeOne( int position )
   {
      if( position >= static_soundsNames.length )
      {
         position = position - static_soundsNames.length;
         String name = mCustomSounds.remove( position );
         mCustomSoundsFilenames.remove( position );
         this.notifyDataSetChanged();
         
         Editor edit = PreferenceManager.getDefaultSharedPreferences( mContext ).edit();
         edit.remove( name );
         edit.commit();
      }
   }
}
